<template>
    <n-menu
        :options="menuTree"
        accordion
        v-model:expanded-keys="expandedKeys"
        v-model:value="currentKey"
    />
</template>

<script setup lang="ts">
import { useAuthMenuStore } from '@/store'
import { storeToRefs } from 'pinia'
import { onMounted, ref } from 'vue'
import { RouteLocationNormalizedGeneric, useRoute } from 'vue-router'

const menuStore = useAuthMenuStore()
const { menuTree } = storeToRefs(menuStore)

const expandedKeys = ref<string[]>([])
const currentKey = ref<string>()

const route = useRoute()

// 初始化路由选中
function initMenuKeys(route: RouteLocationNormalizedGeneric) {
    const name = (route.meta.active || route.name) as string
    const arr = name.split('-')
    currentKey.value = name

    const selectedArr = arr.reduce((acc, part, index) => {
        if (index + 1 === arr.length) {
            return acc
        }

        const newPart = index === 0 ? part : `${acc[acc.length - 1]}-${part}`
        acc.push(newPart)
        return acc
    }, [] as string[])

    expandedKeys.value = selectedArr
}

onMounted(() => {
    initMenuKeys(route)
})
</script>
